package com.dyrj.base.system.apkCtrl.service.impl;


import com.dyrj.base.system.apkCtrl.dao.TCtrlAppVersionMapper;
import com.dyrj.base.system.apkCtrl.model.TCtrlAppVersion;
import com.dyrj.base.system.apkCtrl.service.ApkCtrlService;
import com.dyrj.component.properties.UploadProperties;
import com.dyrj.constant.SysFrameConst;
import com.dyrj.vo.PageResultMsg;
import com.dyrj.vo.ResultMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @Title: TaskServiceImpl.java
 * @Package com.dyrj.base.system.user.service.impl
 * @Description: (任务管理)
 * @author
 * @date 2019年4月13日 下午11:30:23
 * @version V1.0
 */
@Service
@Log4j2
public class ApkCtrlServiceImpl implements ApkCtrlService {


    @Resource
	private TCtrlAppVersionMapper tCtrlAppVersionMapper;
//    @Resource
//    private Scheduler scheduler;
    @Resource
    private UploadProperties uploadProperties;

    @Override
    public PageResultMsg table(TCtrlAppVersion record) {
//        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
//        record.setId(Long.valueOf(loginUser.getAccount()));
        PageInfo<TCtrlAppVersion> list = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> tCtrlAppVersionMapper.selectList(record));
        return new PageResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, list.getTotal(), list.getList());
    }

    @Override
    public PageResultMsg tenant(TCtrlAppVersion record) {
//        PageInfo<TCtrlAppVersion> list = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> tCtrlAppVersionMapper.selectListTenant(record));
          List list = tCtrlAppVersionMapper.selectListTenant(record);
        return new PageResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, 1, list);
    }

//    @Override
//    public JsonResult checkversion(TCtrlAppVersion record) {
//        PageInfo<TCtrlAppVersion> list = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> tCtrlAppVersionMapper.selectListVersion(record));
//        return new JsonResult();
//    }

    @Override
    public ResultMsg add(TCtrlAppVersion record) {
//        record.setId();
        record.setCreatetime(new Date());
        Long id = record.getId();
//        int i = tCtrlAppVersionMapper.selectByName(String.valueOf(record.getId()));
        if(id!=null) {
            return new ResultMsg(SysFrameConst.ResultCode.ACCOUNT_EXIST.CODE, SysFrameConst.ResultCode.ACCOUNT_EXIST.MESSAGE);
        } else {
            tCtrlAppVersionMapper.insertSelective(record);
            return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
        }
    }

    @Override
    public ResultMsg uploadJarFile(MultipartFile apkfile, HttpServletRequest request) {
//        String rootPath = request.getServletContext().getRealPath("/").replace("\\", "/");//上传文件的跟路径
//        log.debug("rootPath:"+rootPath);
        String basePath = uploadProperties.getBasePath();
        log.debug("basePath:"+basePath);
//        final String uploadPath = "uploadjar/" + new SimpleDateFormat("yyyy").format(new Date());//上传的组合路径
        final String uploadPath = "uploadApk";//上传的组合路径
        final String fileName = apkfile.getOriginalFilename(); //上传的文件名
//        String[] suffixs = {"jar","jpg","gif","png","jpeg","txt"};
        String[] suffixs = {"apk"};
        File saveFilePath = new File(basePath + uploadPath);
        File saveFile = new File(basePath + uploadPath,fileName);
        log.debug("saveFilePath:"+saveFilePath);
        log.debug("saveFile:"+saveFile);
        String msg = "";
        if(!saveFilePath.exists())
            saveFilePath.mkdirs();//目录不存在，递归创建
        if(Arrays.asList(suffixs).contains(getSuffix(saveFile.getName())) == false){//上传文件名检查（白名单机制）true:通过，false：没有通过
            return new ResultMsg(SysFrameConst.ResultCode.UPLOAD_FILETYPE_ERROR.CODE, SysFrameConst.ResultCode.UPLOAD_FILETYPE_ERROR.MESSAGE);
        }else{
            try {
                apkfile.transferTo(saveFile);//保存文件
                msg = "文件上传成功";
                Map map_data = new HashMap<String, Object>() {
                    {
                        put("apkurl", uploadPath + "/"+ fileName);
                    }
                };

//                String data = JSONObject.toJSONString(map_data);

                return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE + msg, map_data);

            } catch (Exception e) {
                e.printStackTrace();
                msg = e.getMessage();
            }
        }

        return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE + msg);
    }

    /**
     * 文件后缀
     * @return
     */
    public String getSuffix(String name) {
        String suffix = name;
        if(suffix.contains("."))
            suffix = suffix.substring(suffix.lastIndexOf(".")+1);
        else
            suffix = "";
        return suffix;
    }



    @Override
    public TCtrlAppVersion info(Long id) {
        TCtrlAppVersion tCtrlAppVersion = tCtrlAppVersionMapper.selectByPrimaryKey(id);
        return tCtrlAppVersion;
    }

    @Override
    public ResultMsg update(TCtrlAppVersion record) {
        String msg = "";
        TCtrlAppVersion id = tCtrlAppVersionMapper.selectByPrimaryKey(record.getId());

        tCtrlAppVersionMapper.updateByPrimaryKeySelective(record);


        return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE + msg);
    }

    @Override
    public ResultMsg delete(Long id) {

        tCtrlAppVersionMapper.deleteByPrimaryKey(id);
        return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
    }




}
